<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/8/31
 * Time: 9:42
 */
namespace App\Http\Controllers\Business\Shop\V1\CollectMoney;

use App\Models\Order;
use App\Models\RedEnvelope;
use App\Models\Shop;
use App\Models\ShopUser;
use App\Models\User;
use App\Models\ShopSalesman;
use App\Models\ShopSalesmanDetail;
use Illuminate\Support\Facades\Redis;

class CollectMoney{

    public static function collectMoney($shopuserid,$shopid,$money,$paycode,$type='')
    {
        if(!$shopid || !$money || !$paycode) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $userid = Redis::get('PayCode:'.$paycode);
        $GLOBALS['shopid'] = $shopid;
        if($userid) {
            Redis::expire('PayCode:'.$paycode,100);
            Redis::expire('PayCode:Userid:'.$userid,100);
            $user = User::find($userid);
            $shop = Shop::find($shopid);
            if($user && $shop) {
                //判断是不是超过买单次数限制
                $buynumber = $shop['buynumber'];
                if($buynumber != 0) {
                    if (($type == '0') || ($type == '')) {
                        $ordercount = Order::where('userid', $userid)->where('shopid', $shopid)->where('created_at', '>=', date('Y-m-d') . " 00:00:00")->get()->count();
                        if ($ordercount >= $buynumber) {
                            return ['status' => 'success', 'data' => ['ordernumber' => '', 'isbuylimit' => '1']];
                        }
                    } elseif ($type == '2') {
                        $ordercount = Order::where('userid', $userid)->where('shopid', $shopid)->where('created_at', '>=', date('Y-m-d') . " 00:00:00")->get()->count();
                        if ($ordercount >= $buynumber) {
                            Redis::setex('PayCode:' . $paycode, 20, 'buynumberlimit');
                            return ['status' => 'failed', 'message' => '收款失败'];
                        }
                    }
                }
                if($user['balance'] < $money) {
                    Redis::setex('PayCode:'.$paycode,20,'balance is not enough');
                    //Redis::setex('PayCode:Userid:'.$userid,20,'balance is not enough');
                    return ['status'=>'failed','message'=>'用户余额不足！'];
                }
                $mobile = substr($user['mobile'],7,10);
                $rand = '';
                for($i=0;$i<4;$i++) {
                    $rand .= rand(0,9);
                }
                $ordernumber=date('ymdHis',time()).$rand.$mobile;
                $redenvelope = RedEnvelope::where(array('userid'=>$userid,'status'=>'0'))
                    ->where('minimumamount','<=',$money)->where(function($query) {
                        $query->orWhere('shopid',$GLOBALS['shopid'])->orWhere('shopid','0');
                    })->orderBy('amount','desc')->first();
                if($redenvelope) {
                    $order = Order::where('userid',$userid)->first();
                    if(!$order) {
                        $user->firstordertime = date('Y-m-d H:i:s',time());
                        $user->firstshopname = $shop['name'];
                        $user->save();
                    }
                    $redenvelope->status = '1';
                    $redenvelope->save();
                    $order = new Order();
                    $order->startbalance = User::where('id',$userid)->pluck('balance')->first();
                    User::find($userid)->decrement('balance', $money - $redenvelope['amount'] + env('COMMISSION_MONEY'));
                    User::find($userid)->increment('savemoney', ($money - $redenvelope['amount'] + env('COMMISSION_MONEY'))/2);
                    Shop::find($shopid)->increment('ordernumber', 1);
                    $order->userid = $userid;
                    $order->nickname = $user['nickname'];
                    $order->shopid = $shopid;
                    $order->shopname = $shop['name'];
                    $order->shoplogo = $shop['logo'];
                    $order->ordernumber = $ordernumber;
                    $order->orderamount = $money;
                    if($redenvelope['shopid']) {
                        $order->shopamount = $money - $redenvelope['amount'];
                        $order->fee = env('COMMISSION_MONEY');
                        $order->accountamount = round(($money - $redenvelope['amount'])/2,2);
                    } else {
                        $order->shopamount = $money;
                        $order->fee = env('COMMISSION_MONEY') - $redenvelope['amount'];
                        $order->accountamount = round($money/2,2);
                    }
                    $order->actualamount = $money - $redenvelope['amount'] + env('COMMISSION_MONEY');
                    $order->redenvelopeamount = $redenvelope['amount'];
                    $order->redenvelopeid = $redenvelope['id'];
                    $order->shopuserid = $shopuserid;
                    $order->lastbalance = User::where('id',$userid)->pluck('balance')->first();
                    $comment = Order::where('userid',$userid)->where('shopid',$shopid)
                        ->where('created_at','>',date('Y-m-d 00:00:00',time()))
                        ->where('created_at','<',date('Y-m-d 23:59:59',time()))
                        ->where('commentstatus','1')->first();
                    if($comment)
                    {
                        $order->commentstatus = '2';
                    }
                    $order->save();
                } else {
                    $order = Order::where('userid',$userid)->first();
                    if(!$order) {
                        $user->firstordertime = date('Y-m-d H:i:s',time());
                        $user->firstshopname = $shop['name'];
                        $user->save();
                    }
                    $order = new Order();
                    $order->startbalance = User::where('id',$userid)->pluck('balance')->first();
                    User::find($userid)->decrement('balance', $money + env('COMMISSION_MONEY'));
                    User::find($userid)->increment('savemoney', ($money + env('COMMISSION_MONEY'))/2);
                    Shop::find($shopid)->increment('ordernumber', 1);
                    $order->userid = $userid;
                    $order->nickname = $user['nickname'];
                    $order->shopid = $shopid;
                    $order->shopname = $shop['name'];
                    $order->shoplogo = $shop['logo'];
                    $order->ordernumber = $ordernumber;
                    $order->orderamount = $money;
                    $order->shopamount = $money;
                    $order->fee = env('COMMISSION_MONEY');
                    $order->actualamount = $money + env('COMMISSION_MONEY');
                    $order->accountamount = round($money/2,2);
                    $order->shopuserid = $shopuserid;
                    $order->lastbalance = User::where('id',$userid)->pluck('balance')->first();
                    $comment = Order::where('userid',$userid)->where('shopid',$shopid)
                        ->where('created_at','>',date('Y-m-d 00:00:00',time()))
                        ->where('created_at','<',date('Y-m-d 23:59:59',time()))
                        ->where('commentstatus','1')->first();
                    if($comment)
                    {
                        $order->commentstatus = '2';
                    }
                    $order->save();
                }
                Redis::setex('PayCode:'.$paycode,10,$ordernumber);
                Redis::expire('PayCode:Userid:'.$userid,10);
                self::addShopSalesmanByOrder($userid, $ordernumber, $money, date('Y-m-d H:i:s'));
                return ['status'=>'success','data'=>['ordernumber'=>$ordernumber, 'isbuylimit'=>'0']];
            }
        }
        return ['status'=>'failed','message'=>'收款失败，未查到该订单号！'];
    }

    public static function isCollectMoney($shopid) {
        if(!$shopid) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $shop = Shop::where('id', $shopid)->select('nightevent', 'todayevent', 'status')->first();
        if($shop) {
            if($shop['status'] == '0') {
                //TODO 下架
                return ['status'=>'failed', 'message'=>'门店已下架，请联系客服'];
            }
            if($shop['nightevent'] || $shop['todayevent']) {
                return ['status' => 'success', 'message' => '可以收款'];
            }
        }
        return ['status'=>'failed', 'message'=>'不可以收款'];
    }
    //新增商家地推订单的
    public static function addShopSalesmanByOrder($userId, $orderNumber, $orderAmount, $orderTime) {
        if(!$userId||!$orderNumber||!$orderAmount||!$orderTime||($orderAmount<50)) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $user = User::where('id', $userId)->select('mobile', 'shopid')->first();
        if(!$user) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $shopId = $user->shopid;
        $mobile = $user->mobile;
        if(($shopId == 0) || ($shopId=='')) {
            return ['status'=>'failed','message'=>'不需要添加地推订单'];
        }
        //检测订单是不是在同一天和同一家商家消费过
        $userIsConsumeResult = self::userIsConsume($userId, $orderNumber);
        if($userIsConsumeResult ['status'] == 'failed') {
            return ['status'=>'failed', 'message'=>$userIsConsumeResult['message']];
        }
        $shopSalesman = ShopSalesman::where('shopid', $shopId)->where('status', 1)
            ->select( 'contractstarttime', 'contractlasttime', 'type')->first();
        if(!$shopSalesman) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        $contractStartTime = $shopSalesman->contractstarttime;
        $contractLastTime = $shopSalesman->contractlasttime;
        $shopSalesmanType = $shopSalesman->type;
        if($shopSalesmanType == 'partner') {
            $getMoney = 2;
        } elseif($shopSalesmanType == 'common') {
            $getMoney = 1;
        } else {
            return ['status'=>'failed', 'message'=>'类型不对'];
        }
        if((strtotime($orderTime) < strtotime($contractStartTime . " 00:00:00")) || (strtotime($orderTime) > strtotime($contractLastTime . " 23:59:59"))) {
            return ['status'=>'failed', 'message'=>'合约到期了'];
        }
        //商家地推详情
        $shopSalesmanDetail = ShopSalesmanDetail::create([
            'shopid' => $shopId,
            'shopusermobile' => '',
            'type' => 'order',
            'mobile' => $mobile,
            'getmoney' => $getMoney,
            'ordernumber' => $orderNumber,
            'orderamount' => $orderAmount,
            'ordertime' => date('Y-m-d H:i:s', strtotime($orderTime))
        ]);
        ShopSalesman::where('shopid', $shopId)->increment('balance', $getMoney);
        ShopSalesman::where('shopid', $shopId)->increment('validordernum', 1);
        return ['status'=>'success', 'message'=>'新增成功'];
    }
    //检测订单是不是在同一天和同一家商家消费过
    public static function userIsConsume($userId, $orderNumber) {
        if(!$userId || !$orderNumber) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $order = Order::where('ordernumber', $orderNumber)->where('userid', $userId)->first();
        if(!$order) {
            return ['status'=>'failed', 'message'=>'获取订单失败'];
        }
        $shopId = $order['shopid'];
        $todayStartTime = date('Y-m-d') . " 00:00:00";
        $todayEndTime = date('Y-m-d') . " 23:59:59";
        $count = Order::where('shopid', $shopId)->where('userid', $userId)->where('ordernumber', '!=', $orderNumber)
            ->where('created_at', '>=', $todayStartTime)->where('created_at', '<=', $todayEndTime)
            ->get()->count();
        if($count>0) {
            return ['status'=>'failed', 'message'=>'该用户今天在该商家已买过单'];
        } else {
            return ['status'=>'success', 'message'=>'该用户今天在该商家没买过单'];
        }
    }
}